package com.mrd.frame.onlinepay.query.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.mrd.frame.domain.AccessConfig;
import com.mrd.frame.domain.Order;
import com.mrd.frame.domain.OrderInteraction;
import com.mrd.frame.domain.PayConfig;
import com.mrd.frame.domain.params.PayParams;
import com.mrd.frame.onlinepay.AliPayApi;
import com.mrd.frame.onlinepay.query.IPayQuery;
import com.mrd.frame.service.OrderInteractionService;
import com.mrd.frame.service.OrderService;
import com.mrd.weixinpay.util.ChangeUtil;
import com.mrd.weixinpay.util.HttpUtil;
import com.mrd.weixinpay.util.PayCommonUtil;
import com.mrd.weixinpay.util.XMLUtil;

/**
 * 支付宝查询接口
 * @author han
 */
@Component
public class AliQuery extends AliPayApi implements IPayQuery {
	private static final Logger logger = Logger.getLogger(AliQuery.class);
	@Autowired
	OrderInteractionService orderInteractionService;
	@Autowired
	OrderService orderService;
	
	public Map queryOrder(PayParams payParams, AccessConfig accessConfig,
			Order order) throws Exception {
		Map<Object, Object> restMap = new HashMap<Object, Object>();
		String retRsult = "";
		String reMsg = "";
		String reOrder = "";
		OrderInteraction orderInt = new OrderInteraction();
		orderInt.setCreateTime(new Date());
		orderInt.setOrderId(order.getTradeNo());// 商户提供的订单号
		orderInt.setOrderInteractionId(String.valueOf(System
				.currentTimeMillis()));
		orderInt.setType("D1");

		String out_trade_no = order.getOrderId();// 发送给微信方用于支付请求的订单号

		SortedMap<Object, Object> params = new TreeMap<Object, Object>();
		params.put("out_trade_no", out_trade_no);

		String requestXML = PayCommonUtil.getRequestXml(params);
		logger.info("向支付宝发起查询 请求的参数:" + requestXML);
		// 将查询请求存入交互记录表中
		orderInt.setParameters(requestXML);
		orderInt.setType("D1");
		orderInt.setStatus("0");
		int d1 = orderInteractionService.insert(orderInt);
		String resXml = "";
		try {
			String resultStr = "";
			AlipayTradeQueryModel model = new AlipayTradeQueryModel();
			model.setOutTradeNo(out_trade_no);

			AlipayTradeQueryResponse response = tradeQuery(model,accessConfig.getUserKey());
			
			// 将查询请求返回信息存入记录表中
			orderInt.setType("D2");
			orderInt.setStatus("0");
			int d2 = orderInteractionService.insert(orderInt);

			String code = response.getCode();
			String msg = response.getMsg();
			String subCode = response.getSubCode();
			String subMsg = response.getSubMsg();
			String tradeStatus = response.getTradeStatus();//订单状态
			if (code.equals(AliCodeEnu.CECUSS.val())) {
				// trade_state: SUCCESS—支付成功 ，REFUND—转入退款
				// ,NOTPAY—未支付（用户一直没有支付，或者超过时间没有支付）
				// ,CLOSED—已关闭 ,
				// REVOKED—已撤销（刷卡支付） ，USERPAYING--用户支付中（调起密码框后没有输入密码）
				// ，PAYERROR--支付失败(其他原因，如银行返回失败）

				if (AliTradeStatus.TRADESUCCESS.val().equals(tradeStatus)) {
					// 支付已完成，修改支付系统的订单号为支付完成状态
					order.setStatus("2");
					//TRADECLOSED
					//TRADEFINISHED
				} else if (tradeStatus.equals(AliTradeStatus.TRADECLOSED.val())
						|| tradeStatus.equals(AliTradeStatus.TRADEFINISHED.val())) {
					// 订单状态 0：处理失败
					order.setStatus("0");
				} else if (tradeStatus.equals(AliTradeStatus.WAITBUYERPAY.val())) {
					// 判断时间差，下单超过两小时就将订单状态改为超时
					Date staTime = order.getTimeStart();
					long timeInterval = ChangeUtil.getTimeInterval(new Date(),
							staTime);
					if (timeInterval >= (2 * 60)) {
						order.setStatus("3");
					}
				}
				int r1 = orderService.updateByPrimaryKeySelective(order);
				retRsult = "SUCCESS";
				reMsg = subMsg;
			} else {
				if (subCode.equals(AliQueryEnu.MISPARAM.val())) {
					reMsg = "此交易订单号不存在 ";
				} else {
					reMsg = "系统异常请再次调用重新查询";
				}
				retRsult = "FILE";
			}
			restMap.put("retRsult", retRsult);
			restMap.put("reMsg", reMsg);
			restMap.put("reOrder", order);
			// 吊起查询接口，确认订单状态

		} catch (Exception e) {
			orderInt.setType("D2");
			orderInt.setStatus("1");
			int d2 = orderInteractionService.insert(orderInt);
			retRsult = "FILE";

		}

		return restMap;
	}

}
